package com.manlitech.cloudboot.oauth.config.filter;

import com.alibaba.druid.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 校验jwt是否有效，是否有权限
 * @author shensg
 * @date 2021/7/7 18:07
 */
@Slf4j
public class JwtAuthorizationFilter  extends BasicAuthenticationFilter {

    Logger logger = LoggerFactory.getLogger(JwtAuthorizationFilter.class);

    public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        Authentication authentication= getAuthentication(request);
        if(authentication==null){
            filterChain.doFilter(request,response);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request,response);

    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        //&&token.startsWith("Bearer"
        if(!StringUtils.isEmpty(token)){
            //盐
            String  signKey="NDU0NTY4amhmc3NkeHp6eGNxdzIlMjFAJTIxQCUyM2ZmNQ==";
            Claims claims = null;
            try {
                claims = Jwts.parser().setSigningKey(signKey).parseClaimsJws(token).getBody();
            } catch (Exception e) {
                return null;
            }
            String username =claims.getSubject();
            List<String> roles = (List<String>) claims.get("roles");
            List<SimpleGrantedAuthority> collect = roles.stream().map(authority -> new SimpleGrantedAuthority((String) authority)).collect(Collectors.toList());

            if(!StringUtils.isEmpty(username)){
                return new UsernamePasswordAuthenticationToken(username,null,collect);
            }
        }
        return null;
    }
}
